package com.aispeech.task.executor.config;

import com.aispeech.task.common.handler.TaskHandler;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;

@Slf4j
@Configuration
@ConfigurationProperties(prefix = "task.handler")
@Data
public class TaskConfig {
    private String jarPath;
    private String className;
    private int eventThreads;

    @Bean
    TaskHandler taskHandler() throws MalformedURLException, ClassNotFoundException, IllegalAccessException, InstantiationException {
        log.warn("***** Task handler *********************************************\t\t");
        log.warn("\t[ FROM  ]: {}\t\t", jarPath);

        URL url = new URL("file:" + jarPath);

        URLClassLoader loader = new URLClassLoader(new URL[]{url}, Thread.currentThread().getContextClassLoader());
        Class<? extends TaskHandler> cls = (Class<? extends TaskHandler>) loader.loadClass(className);

        log.warn("\t[ CLASS ]: {}\t\t", className);

        TaskHandler taskHandler = cls.newInstance();

        log.warn("****************************************************************\t\t");

        return taskHandler;
    }
}
